package com.piece.blog.event;

import com.piece.blog.model.Article;
import com.piece.blog.service.ArticleService;
import com.piece.core.framework.support.dto.PayloadDTO;
import com.piece.core.framework.util.message.MessageFactory;
import com.piece.core.framework.util.string.JsonUtil;
import com.piece.core.mongo.entity.MongoMessageLog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Slf4j
@Component
public class ArticlePostEventHandler implements ApplicationListener<ArticlePostEvent> {

    @Resource
    private ArticleService articleService;

    @Resource
    private MessageFactory messageFactory;

    @Async
    @Override
    public void onApplicationEvent(ArticlePostEvent event) {
        if (null == event) {
            return;
        }

        Article article = event.getArticle();
        MongoMessageLog messageLog = new MongoMessageLog();
        messageLog.setEntity(JsonUtil.toJson(article));

        switch (event.getAction()) {
            case ArticlePostEvent.ACTION_PUBLISH:
                messageLog.setTitle("发布文章");
                messageLog.setMethod("articleService.publicMessage");
                break;
            case ArticlePostEvent.ACTION_UPDATE:
                messageLog.setTitle("更新文章");
                messageLog.setMethod("articleService.updateMessage");
                return;
            case ArticlePostEvent.ACTION_DELETE:
                messageLog.setTitle("删除文章");
                messageLog.setMethod("articleService.deleteMessage");
                return;
            case ArticlePostEvent.ACTION_FAVOR:
                messageLog.setTitle("收藏文章");
                messageLog.setMethod("articleService.favorMessage");
                break;
            case ArticlePostEvent.ACTION_COMMENT:
                messageLog.setTitle("发布新评论");
                messageLog.setMethod("articleService.commonMessage");
                articleService.addCommon(messageLog.getEntity());
                break;
            case ArticlePostEvent.ACTION_VIEW:
                articleService.viewMessage(messageLog.getEntity());
                return;
        }

        try {
            PayloadDTO payload = new PayloadDTO();
            payload.setEntity(JsonUtil.toJson(messageLog));
            messageFactory.get().send(payload);
        } catch (Exception e) {
            log.error("文章事件发送消息失败：{}", e.getMessage());
        }
    }
}
